<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div class="box">
          <el-button type="success" icon="el-icon-edit" @click="goRouter">
            新增试题
          </el-button>
        </div>
        <!-- 表单 -->
        <el-form ref="formName" :model="ruleForm" label-width="70px" size="small">
          <el-row>
            <el-col :span="6">
              <el-form-item label="学科">
                <el-select v-model="ruleForm.subjectsName" placeholder="请选择" @change="getTagsList($event)">
                  <el-option
                    v-for="item in subjectsList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select v-model="ruleForm.directorys" placeholder="请选择">
                  <el-option
                    v-for="item in directorysList"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.directoryName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select v-model="ruleForm.tagName" placeholder="请选择">
                  <el-option
                    v-for="item in tagsList"
                    :key="item.id"
                    :label="item.tagName"
                    :value="item.tagName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键字">
                <el-input v-model="ruleForm.keyword" placeholder="根据题干搜索"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="试题类型">
                <el-select v-model="ruleForm.questionType" placeholder="请选择">
                  <el-option
                    v-for="item in questionList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度">
                <el-select v-model="ruleForm.difficulty" placeholder="请选择">
                  <el-option
                    v-for="item in difficultyList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向">
                <el-select v-model="ruleForm.direction" placeholder="请选择">
                  <el-option
                    v-for="item in directionList"
                    :key="item.id"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录入人">
                <el-select v-model="ruleForm.username" placeholder="请选择">
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.username"
                    :value="item.username"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="题目备注">
                <el-input v-model="ruleForm.titleRemarks"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input v-model="ruleForm.tags"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="城市">
                <el-row>
                  <el-col :span="12">
                    <el-select v-model="ruleForm.provinces" placeholder="请选择" @change="getprovincesList($event)">
                      <el-option
                        v-for="item in provincesList"
                        :key="item.id"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="12">
                    <el-select v-model="ruleForm.citys" placeholder="请选择">
                      <el-option
                        v-for="item in citysList"
                        :key="item.id"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-row>
                <el-col :span="5" :offset="14">
                  <el-button @click="resetForm()">清除</el-button>
                </el-col>
                <el-col :span="5">
                  <el-button type="primary" @click="search()">搜索</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <!-- 题库列表 -->
        <el-tabs
          v-loading="isLoading"
          v-model="activeName"
          type="card"
          @tab-click="handleClick">
          <el-tab-pane
            v-for="(item, index) in TabPane"
            :key="index"
            :label="item"
            activeName="$createElement[index]">
            <el-alert
              type="info"
              :closable="closebool"
              show-icon>
              数据一共{{counts}}条
            </el-alert>
            <!-- 表格数据 -->
            <!-- #default="row" -->
            <el-table
              :data="tableDataList"
              style="width: 100%"
              max-height="500">
              <el-table-column
                prop="number"
                label="试题编号"
                width="150">
              </el-table-column>
              <el-table-column
                prop="subject"
                label="学科"
                width="120">
              </el-table-column>
              <el-table-column
                prop="catalog"
                label="目录"
                width="120">
              </el-table-column>
              <el-table-column
                prop="questionType"
                label="题型"
                width="120"
                :formatter="questionTypeEmpment">
              </el-table-column>
              <el-table-column
                prop="question"
                label="题干"
                width="200">
                <template #default="{row}">
                  <div v-html="row.question"></div>
                </template>
              </el-table-column>
              <el-table-column
                prop="addDate"
                label="录入时间"
                width="150"
                :formatter="addDateEmpment">
              </el-table-column>
              <el-table-column
                prop="difficulty"
                label="难度"
                width="120"
                :formatter="difficultyEmpment">
              </el-table-column>
              <el-table-column
                prop="creator"
                label="录入人"
                width="120">
              </el-table-column>
              <el-table-column
                prop="chkState"
                label="审核状态"
                width="120"
                :formatter="chkStateEmpment">
              </el-table-column>

              <el-table-column
                prop="chkRemarks"
                label="审核意见"
                width="120">
              </el-table-column>
              <el-table-column
                prop="chkUser"
                label="审核人"
                width="120">
              </el-table-column>
              <el-table-column
                prop="state_pub"
                label="发布状态"
                width="120"
                :formatter="state_pub">
              </el-table-column>
              <!-- 操作按钮 -->
              <el-table-column
                fixed="right"
                label="操作"
                width="200"
                align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="previewBtn(scope)">
                    预览
                  </el-button>
                  <!-- auditDisabled -->
                  <el-button
                  type="text"
                    size="small"
                    :disabled="scope.row.chkState === 0 ? false : true"
                    @click="auditBtn(scope)">
                    审核
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    :disabled="scope.row.publishState === 1 && scope.row.chkState === 1 ? true : false"
                    @click="reviseBtn(scope)">
                    修改
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="ShelvesBtn(scope)"
                    >
                    {{ scope.row.publishState == 0 ? publishStateText='上架':publishStateText='下架' }}
                  </el-button>
                  <!-- :disabled="deleteDisabled" -->
                  <el-button
                    type="text"
                    size="small"
                    :disabled="scope.row.publishState === 1 && scope.row.chkState === 1 ? true : false"
                    @click="deleteBtn(scope)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin:10px;display:flex;justify-content:flex-end"
              background
              :current-page="pageData.page"
              :page-sizes="[5,10,20,50]"
              :page-size="pageData.pagesize"
              layout="sizes, prev, pager, next, jumper"
              :total="pages"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
            </el-pagination>
          </el-tab-pane>
        </el-tabs>
        <choice-dialog
          :choice-show-dialog.sync="choiceShowDialog"
          :choice-data="choiceData"
          :audit-show-dialog.sync="auditShowDialog"
          :id="id"
          :options-data="optionsData"
          @getChoiceList="getChoiceList"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
// 精选题库、上下架、删除
import { choice, choicePublish, remove, detail } from '@/api/hmmm/questions'
// 学科列表
import { simple } from '@/api/hmmm/subjects'
// 目录列表
import { list as directorysSimple } from '@/api/hmmm/directorys'
// 标签列表
import { list as tagsSimple } from '@/api/hmmm/tags'
// 用户列表（录入人）
import { list } from '@/api/base/users'
// 城市、区，列表
import { provinces, citys } from '@/api/hmmm/citys'

// 数据格式化处理文件
import { questionTypes, difficulty, chkType, direction } from '@/api/hmmm/constants'
// 时间格式化处理
import dayjs from 'dayjs'

// 弹窗插件
import choiceDialog from './companys/choice-dialog.vue'
export default {
  data () {
    return {
      ruleForm: {
        subjectsName: '',
        directorys: '',
        tagName: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        username: '',
        titleRemarks: '',
        tags: '',
        provinces: '',
        citys: ''
      },
      ShelvesForm: {
        id: null,
        publishState: null
      },
      TabPane: ['全部', '待审核', '已审核', '已拒绝'],
      // 警告框布尔值
      closebool: false,
      tableData: [],
      activeName: '0',
      // 总题数量
      counts: 0,
      // 当前页码
      pageData: {
        page: 1,
        // 页大小
        pagesize: 5
      },
      // 总页数
      pages: null,
      // 筛选列表
      tableDataList: [],
      // 加载等待
      isLoading: false,
      // 学科列表
      subjectsList: [],
      // 标签列表
      tagsList: [],
      // 目录列表
      directorysList: [],
      // 试题类型列表
      questionList: questionTypes,
      // 难度列表
      difficultyList: difficulty,
      // 方向列表
      directionList: direction,
      // 录入人列表
      userList: [],
      // 城市、区
      provincesList: [],
      citysList: [],

      // 预览弹窗显示
      choiceShowDialog: false,
      // 编辑信息
      choiceData: [],
      // 审核弹窗显示
      auditShowDialog: false,
      // 审核id
      id: null,
      // 上下架文本
      publishStateText: '上架',
      // 题型数据
      optionsData: []
    }
  },
  components: {
    choiceDialog
  },
  created () {
    this.getChoiceList()
    this.subjectsNameList()
    this.userNameList()
    this.provincesNameList()
  },
  methods: {
    // 筛选题库
    handleClick (tab, event) {
      // console.log(tab)
      // this.getChoiceList()
      if (tab.index === '0') {
        this.getChoiceList()
      }
      if (tab.index === '1') {
        const newtableData = this.tableData.filter(item => item.chkState === Number(0))
        this.tableDataList = newtableData
      }
      if (tab.index === '2') {
        const newtableData = this.tableData.filter(item => item.chkState === Number(1))
        this.tableDataList = newtableData
      }
      if (tab.index === '3') {
        const newtableData = this.tableData.filter(item => item.chkState === Number(2))
        this.tableDataList = newtableData
      }
    },
    // 题型数据格式处理
    questionTypeEmpment (row, column, cellValue, index) {
      const question = questionTypes
      const result = question.find(item => item.value === cellValue)
      return result ? result.label : '未知'
    },
    // 困难度格式化处理
    difficultyEmpment (row, column, cellValue, index) {
      const diff = difficulty
      const result = diff.find(item => item.value === cellValue)
      return result ? result.label : '未知'
    },
    // 审核状态格式化处理
    chkStateEmpment (row, column, cellValue, index) {
      const chk = chkType
      const result = chk.find(item => item.value === cellValue)
      return result ? result.label : '未知'
    },
    // 发布状态格式化处理
    state_pub (row) {
      if (row.publishState === 1 && row.chkState === 1) {
        return '已发布'
      } else if (row.publishState === 0 && row.chkState === 1) {
        return '已下架'
      } else {
        return '待发布'
      }
    },
    // 时间处理
    addDateEmpment (row, column, cellValue, index) {
      return dayjs(cellValue).format('YYYY-MM-DD hh:mm:ss')
    },
    // 搜题
    search () {
      const newtableData = this.tableData.filter(item => item.subject === this.ruleForm.subjectsName)
      this.tableDataList = newtableData
    },
    // 页码容量变化
    handleSizeChange (val) {
      this.pageData.pagesize = val
      this.pageData.page = 1
      this.getChoiceList()
      // console.log(val)
    },
    // 页码变化
    handleCurrentChange (val) {
      this.pageData.page = val
      this.getChoiceList()
      // console.log(val)
    },
    // 获取精选题库
    async getChoiceList () {
      this.isLoading = true
      const { data } = await choice(this.pageData)
      this.pages = data.pages * data.pagesize
      this.tableData = data.items
      this.tableDataList = this.tableData
      console.log(data)
      this.counts = data.counts
      this.isLoading = false
    },
    // 跳转到新增题库
    goRouter () {
      this.$router.push('new')
    },

    // 获取学科名称
    async subjectsNameList () {
      const { data } = await simple()
      this.subjectsList = data
    },
    // 获取、标签
    async getTagsList (subject) {
      // this.ruleFrom.tagName = ''
      const newPage = {
        page: 1,
        pagesize: 100
      }
      const { data: tagsData } = await tagsSimple(newPage)
      this.tagsList = tagsData.items.filter(item => item.subjectName === subject)
      const { data: directorysData } = await directorysSimple(newPage)
      this.directorysList = directorysData.items.filter(item => item.subjectName === subject)
    },
    // 获取录入人列表
    async userNameList () {
      const { data } = await list()
      // console.log(data.list)
      this.userList = data.list
    },
    // 获取城市列表
    async provincesNameList () {
      const data = await provinces()
      this.provincesList = data
    },
    async getprovincesList (provinces) {
      this.ruleForm.citys = ''
      const dataChild = await citys(provinces)
      this.citysList = dataChild
    },
    // // 清空表单
    resetForm () {
      this.ruleForm = {
        subjectsName: '',
        directorys: '',
        tagName: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        username: '',
        titleRemarks: '',
        tags: '',
        provinces: '',
        citys: ''
      }
      this.citysList = []
      this.tagsList = []
      this.directorysList = []
      this.getChoiceList()
    },
    // 预览按钮
    async previewBtn (scope) {
      console.log(scope.row.questionType, '精选预览')
      this.choiceData = scope.row
      this.choiceShowDialog = true
      const { data } = await detail(scope.row.id)
      this.optionsData = data.options
    },
    // 审核按钮
    auditBtn (scope) {
      this.id = scope.row.id
      this.auditShowDialog = true
    },
    // 跳转修改
    reviseBtn (scope) {
      this.id = scope.row.id
      this.$router.push({
        path: 'new/',
        query: {
          id: this.id
        }
      })
    },
    // 上下架提交
    ShelvesBtn (scope) {
      this.$confirm(`您确认${scope.row.publishState === 0 ? this.publishStateText = '上架' : this.publishStateText = '下架'}这道题目吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.ShelvesForm.id = scope.row.id
        if (scope.row.publishState === 0) {
          this.ShelvesForm.publishState = 1
        } else {
          this.ShelvesForm.publishState = 0
        }
        console.log(this.ShelvesForm, '上下架')
        const data = await choicePublish(this.ShelvesForm)
        console.log(data)
        this.$message({
          type: 'success',
          message: `${scope.row.publishState === 0 ? this.publishStateText = '上架' : this.publishStateText = '下架'}成功!`
        })
        this.getChoiceList()
      }).catch((res) => {
        console.log(res)
      })
    },
    // 删除该项
    deleteBtn (scope) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(scope)
        await remove(scope.row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.pages--
        }
        this.getChoiceList()
      }).catch((res) => {
        console.log(res)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.box{
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
  padding-right: 10px;
}
::v-deep {
  .el-button[type="success"]{
    margin-bottom: 10px;
  }
  .el-button {
    padding: 9px 15px;
    font-size: 12px;
  }
  .el-form {
    .el-input {
      padding: 0 10px 0 0;
    }
    .el-input__inner {
      padding-right: 60px;
    }
    .el-input--suffix {
      padding-right: 7px;
    }
    .el-input__icon {
      width: 40px;
    }
  }
  .el-table{
    .el-button{
      padding: 9px 0px;
    }
  }
  .el-alert{
    margin-bottom: 10px;
  }
}
</style>
